package com.tevintao.marketingsystem.task;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.provider.ChatMessageBean;
import com.tevintao.marketingsystem.provider.FriendProvider;
import com.tevintao.marketingsystem.provider.LastUpdateDB;
import com.tevintao.marketingsystem.provider.ChatNewMessageProvider;
import com.tevintao.marketingsystem.provider.ChatNewChatDB;
import com.tevintao.marketingsystem.services.MockServices;
import com.tevintao.marketingsystem.services.TaskLogicService;
import com.tevintao.marketingsystem.services.ViewOperation;
import com.tevintao.marketingsystem.tool.ClassTool;
import com.tevintao.marketingsystem.xposted.HookAudioRecord;
import com.tevintao.marketingsystem.xposted.WxTaskManger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Objects;


/**
 * 自己人聊天
 */
public class BussinessCheckTaskProcess extends SetTaskExtra {
    private static BussinessCheckTaskProcess ourInstance = new BussinessCheckTaskProcess();

    public static BussinessCheckTaskProcess getInstance() {
        return ourInstance;
    }

    private BussinessCheckTaskProcess() {
    }

    private ChatMessageBean mNewChat;

    private long lastUpdate = 0;

    private boolean needSyncBaseFriend = true;
    private boolean needSyncFriend = true;

    private Uri friendsUri = Uri.parse("content://report_new_friends");


    private boolean waitOneStemp = false;//收到红包后，等待一个会和在处理消息

    private int searchFailedTimes = 0;//搜索失败次数

    @SuppressWarnings("ResourceType")
    private boolean reportAllNewMessage(ViewGroup v) {
        if (waitOneStemp) {
            waitOneStemp = false;
        }
        HideKeyboard(v);

        View listView = v.findViewById(2131624768);
        LogManager.getInstance().logInfo("listView = " + listView);
        if (null == listView) {
            LogManager.getInstance().logError("reportNewMessage null == listView");
            return false;
        }

        ListView lv = (ListView) listView;
        Adapter adapter = lv.getAdapter();

        String field_talker = getCurrentChatWxId(lv);
        //先拿到微信id
        LogManager.getInstance().logInfo("微信ID = " + field_talker);
        if (TextUtils.isEmpty(field_talker)) {
            LogManager.getInstance().logError("获取field_talker 失败");
            return false;
        }

        //// TODO: 2017/3/22 检查最后的消息，是否已经删除了好友
        //// TODO: 2017/3/22 检查最后的消息，是否已经删除了好友

        long lastSendTime = LastUpdateDB.getChatLastTime(v.getContext(), field_talker);
        if (lastSendTime <= 0) {
            LogManager.getInstance().logError("这个好友 之前不存在的消息");
        }

        /**
         * 如果数据库中没有这个好友的最后消息时间，就取到listview的第一个
         */
        if (LastUpdateDB.GET_LAST_TIME_FAIL == lastSendTime) {
            for (int i = 0; i < adapter.getCount(); i++) {
                Object item = adapter.getItem(i);

                Object field_createTime_Obj = getObjField(item, "field_createTime");
                if (null != field_createTime_Obj && field_createTime_Obj instanceof Long) {
                    lastSendTime = (long) field_createTime_Obj;
                    LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastSendTime);
                    LogManager.getInstance().logInfo("之前没有最后的消息，就让第一条消息的时间作为最后的时间  field_createTime_Obj = " + field_createTime_Obj);
                    break;
                }
            }
        }

        LogManager.getInstance().logInfo("开始检测新消息  lastSendTime = " + lastSendTime);

        /**
         *  下面开始开始处理可能会有滚动消息
         *  当第一条消息不是最新的消息的时候，需要向上滚动，
         *  当最后一条消息不是listview lastvisiblepostion的时候，就向下滚动
         *
         * 消息的第一条和最后一条可能出到屏幕外一半，所以检查的时候无视处理
         */

        int firstPosition = lv.getFirstVisiblePosition();
        int lastPosition = lv.getLastVisiblePosition();


        /**
         * 检查是否需要上滑，必须判断是手机接收到的消息，要不可能会异常
         * 在检查上下滚动的时候，是否需要必须检查是对方发送来的消息呢，  没必要，因为不管是发送还是接收的消息，时间线都是连续的。
         *
         * 检查第一个接收到的消息即可
         *
         * 滚动之后是否会陷入死循环
         *
         * 特例1 【【如果滑动到顶端的话, firvisual == 0】】
         * 特例2 【【当前页面如果全是自己发送的消息的话】】，把时间指向当前页面末尾的时间，
         * 特例3【【如果一条消息占据一屏幕呢，只有文字消息会】】
         * 特例3 【【如果滑动上去之后，接收到消息只查到一条是已经处理过的消息的话】】，就把时间指向所有消息当前页面的最后时间
         * 特例4 【【当第一屏幕就是一条消息呢】】
         */

        /**
         * 最后确认，只需要沿着时间线往下，挨个处理即可解决问题。
         */


        /**
         * 当只有一条消息的时候，或者说是一屏幕的时候，的判断，  0 == FirstVisiblePosition
         */

        int firstProcessPosition = firstPosition + 1;
        int lastProcessPosition = lastPosition; //因为循环是小于，所以最后一个不会执行

        /**
         * 处理一下开头在最上方，或者开头是红包
         */
        if (0 == firstPosition) {
            firstProcessPosition = 0;
        } else if (firstProcessPosition >= lastProcessPosition) { //当只有几条消息的时候
            LogManager.getInstance().logError("firstProcessPosition >= lastProcessPosition");
        }


        LogManager.getInstance().logInfo("开始检测新消息  firstProcessPosition = " + firstProcessPosition + " lastPosition = " + lastPosition);

        long lastProcessMessage = lastSendTime;
        for (int i = firstProcessPosition; i < lastProcessPosition; i++) {
            Object item = adapter.getItem(i);
            long currentItemTime = getItemTime(item);
            LogManager.getInstance().logInfo("----------- 检测消息 position = " + i + " currentItemTime = " + currentItemTime + " lastSendTime = " + lastSendTime + " isReceivedMessage = " + isReceivedMessage(item));
            if (i == firstProcessPosition) { //第一个显示用于判断是否 需要上滑动
                if (currentItemTime > lastProcessMessage && 0 != firstPosition /**保证第一个消息不是第一条，*/) { //当前item时间大于最后时间，需要上滑
                    scrollUp(lv);
                    LogManager.getInstance().logInfo("第一条处理的消息大于最后发送消息时间，向上移动");
                    return true;
                }
            }
            //不需要上滑动那就沿着时间线处理所有item
            if (currentItemTime > lastProcessMessage) { //非第一条处理消息大于最后发送消息时间，就处理这个消息
                lastProcessMessage = currentItemTime; //保存最后处理消息的时间
                LogManager.getInstance().logInfo("消息大于最后时间线 保存时间线  position = " + i + " currentItemTime = " + currentItemTime);
                if (isReceivedMessage(item)) { //当前消息是手机接到的消息，开始处理
                    boolean needBack = processReceivedMessage(v, item);
                    LogManager.getInstance().logInfo(" needBack  ===  " + needBack);
                    if (needBack) {
                        clickHongbaoOrZhuanZhangItem = item;
                        clickHongbao2(lv, i);
                        LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastProcessMessage);
                        return true;
                    }
                } else {
                    LogManager.getInstance().logInfo("position = " + i + " 不是手机接收到的消息");
                }
            }
        }

        if (lastProcessMessage > lastPosition) {
            LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastProcessMessage); //最后时间更新 保存最后处理的任务时间
        }
        LogManager.getInstance().logInfo(" ++++++++++++++++++++ 循环完毕 保存时间 lastProcessMessage = " + lastProcessMessage);
        /**
         * 最后一行有可能是 最后的消息，也可能是需要滚动的最后一条消息
         * 最后一行消息单独处理，避免是红包等需要操作的任务的时候，显示一小部分，导致点击失败，
         * 考虑到最后一条消息是红包，每次都需要滚动，所以加上一个滚动一次判断
         */

        if (lastPosition == adapter.getCount() - 1) {  //当前界面末尾已经是最后的消息了
            LogManager.getInstance().logInfo("当前界面末尾已经是最后的消息了");
            Object item = adapter.getItem(lastPosition);
            if (!isReceivedMessage(item)) {
                LogManager.getInstance().logError("||||| 当前消息是自己发送的消息  |||||||||");
                LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastProcessMessage);
                View backButton = v.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
                if (null != backButton) {
                    ViewOperation.clickView(backButton);
                }
                return true;
            }
            long currentItemTime = getItemTime(item);
            if (currentItemTime == lastProcessMessage) {
                LogManager.getInstance().logError("最后一条消息的时间就是 ，最后发送消息的时间，完毕");
            }
            if (currentItemTime > lastProcessMessage) { //如果最后一条消息没有处理，
                lastProcessMessage = currentItemTime;
                LogManager.getInstance().logInfo("最后消息处理  currentItemTime > lastProcessMessage   currentItemTime = " + currentItemTime);
                if (needScrollNext(item)) {
                    if (!hasScrollNext) {
                        LogManager.getInstance().logInfo("最后消息处理  最后需要滚动");
                        hasScrollNext = true;
                        scrollNext(lv);
                        LogManager.getInstance().logInfo("当前界面末尾已经是最后的消息了 最后一条消息是红包需要滚动到下一屏幕");
                    } else {
                        LogManager.getInstance().logInfo("最后消息处理  不需要滚动，处理消息");
                        hasScrollNext = false;
                        boolean needBack = processReceivedMessage(v, item);
                        if (needBack) {
                            clickHongbaoOrZhuanZhangItem = item;
                            clickHongbao2(lv, lastPosition);
                            LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastProcessMessage);
                            return true;
                        }
                        LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastProcessMessage);
                    }
                    return true;
                } else { //最后一条消息不是需要点击的消息就直接处理掉
                    LogManager.getInstance().logInfo("最后一条消息不是需要点击的消息就直接处理掉");

                    processReceivedMessage(v, item);
                    LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, lastProcessMessage);
                    View backButton = v.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
                    if (null != backButton) {
                        ViewOperation.clickView(backButton);
                    }
                }
            } else { //当最后一条消息已经处理过了，就直接返回
                LogManager.getInstance().logInfo("当最后一条消息已经处理过了，就直接返回");
                View backButton = v.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
                if (null != backButton) {
                    ViewOperation.clickView(backButton);
                }
            }
        } else {//当前界面末尾不是所有消息的末尾，就移动到下一屏幕
            scrollNext(lv);
            LogManager.getInstance().logInfo("当前界面末尾不是所有消息的末尾，就移动到下一屏幕");
        }
        return false;
    }

    private Object clickHongbaoOrZhuanZhangItem = null; //重构后的红包暂时记录
    private String clickHongbaoNike = ""; //重构后点击红包时候的昵称，用于 领取红包后，保存名字

    @SuppressWarnings("ResourceType")
    @Override
    public boolean processView(String contextName, View v) {
        LogManager.getInstance().logError(" ------------------------------------------------------------------ " + contextName + " -------------------------------------------- " + MockServices.getProcessName());
        if (WxUiViewConfig.MAIN_LAUNCH.equals(contextName)) {
            if (System.currentTimeMillis() - lastUpdate > 10 * 60 * 1000) {
                needSyncBaseFriend = true;
                needSyncFriend = true;
                lastUpdate = System.currentTimeMillis();
            }

            if (needSyncFriend) {
                return syncFriend(v);
            }

            View chatViewGroupView = v.findViewById(WxUiViewConfig.CHAT_VIEW_GROUP_VIEW);
            if (null != chatViewGroupView && chatViewGroupView.getVisibility() == View.VISIBLE) {
                //聊天界面已经打开
                LogManager.getInstance().logInfo("聊天界面已经打开");
                if (null == mNewChat) {
//                    return reportNewMessage((ViewGroup) v);
                    return reportAllNewMessage((ViewGroup) v);
                } else {
                    return sendChatViewProcess((ViewGroup) v);
                }
            }

            //没打开聊天界面的话，就点击到微信选项
            if (!WxUiViewConfig.inTab(v, WxUiViewConfig.TAB_WEIXIN)) {
                return true;
            }


            //测试双击
//            View tagView = v.findViewWithTag(WxUiViewConfig.TAB_WEIXIN);
//            if (null == tagView) {
//                LogManager.getInstance().logError("checkNewMessage null == tagView  ");
//                return false;
//            }
//            View weixinRedPositon = tagView.findViewById(WxUiViewConfig.TAB_ICO_NEW_MESSAGE_NUM);
//            if (null != weixinRedPositon && weixinRedPositon.getVisibility() == View.VISIBLE) {
//                LogManager.getInstance().logInfo("双击");
//                ViewOperation.clickView(weixinRedPositon);
//            }
            //测试双击


            return checkNewMessage(v);

        } else if (WxUiViewConfig.VIEW_MAIN_LAUNCHER_SEARCH.equals(contextName)) {
            if (null == mNewChat) {
                sendBackEvent(v.getContext());
                return true;
            }


            View editText = v.findViewById(WxUiViewConfig.ID_SEARCH_EDIT_TEXT);
            if (editText != null && editText instanceof EditText) {
                Object searchName = mNewChat.getNickName();
                TextView inputView = (TextView) editText;
                if (searchName.toString().equals(inputView.getText().toString())) {
                    LogManager.getInstance().logInfo("已经输入内容");


                    //////////
                    View searchListView = v.findViewById(2131625775);
                    if (null == searchListView || !(searchListView instanceof ListView)) {
                        LogManager.getInstance().logError("VIEW_MAIN_LAUNCHER_SEARCH  null == searchListView || !(searchListView instanceof ListView)");
                        return false;
                    }

                    ListView listView = (ListView) searchListView;
                    int firstView = listView.getFirstVisiblePosition();
                    Adapter adapter = listView.getAdapter();

                    for (int i = 0; i < listView.getChildCount(); i++) {
                        LogManager.getInstance().logInfo("---------------------------------------------------------------------------------------");
//                        WxUiViewConfig.printViewGroup((ViewGroup) listView.getChildAt(i));
                        Object item = adapter.getItem(i + firstView);
//                        ClassTool.justPrintAllField(item);
//                        ClassTool.PrintGiveFieldAllFiled(item, "kOI");
//                        LogManager.getInstance().logInfo("////////////////////////////////////////////////////////////////////////////////////////////////");
//                        ClassTool.PrintGiveFieldAllFiled(item, "kOJ");

//                        Object koi = getSearchUserNamekOI(item);
//                        Object koj = getSearchUserNamekOJ(item);
                        Object userNameObj = getSearUserName(item);
                        if (null != userNameObj && userNameObj.toString().equals(mNewChat.getTalker())) {
                            LogManager.getInstance().logInfo("找到搜索好友  userNameObj = " + userNameObj + " mNewChat.getTalker() = " + mNewChat.getTalker());
                            ViewOperation.clickView(listView.getChildAt(i));
                            searchFailedTimes = 0;
                            return true;
                        }
                        LogManager.getInstance().logInfo("koi = " + userNameObj);

                        LogManager.getInstance().logInfo("---------------------------------------------------------------------------------------");
                    }


                    searchFailedTimes++;
                    if (searchFailedTimes > 2) {
                        searchFailedTimes = 0;
                        boolean deleteMessage = ChatMessageBean.deleteChatMessage(v.getContext(), mNewChat.getId());
                        LogManager.getInstance().logInfo("删除消息 " + deleteMessage + " id = " + mNewChat.getId());

                        Bundle bundle = new Bundle();
                        bundle.putString(TaskLogicService.KEY_ERROR_MESSAGE, "没有搜索到好友 type " + mNewChat.getType() + " content = " + mNewChat.getContent() + " id = " + mNewChat.getId() + " mNewChat.getTalker() = " + mNewChat.getTalker());
                        Intent errorIntent = new Intent(TaskLogicService.ACTION_REPORT_SYSTEM_ERROR);
                        errorIntent.putExtras(bundle);
                        v.getContext().sendBroadcast(errorIntent);


                        sendBackEvent(v.getContext());
                        mNewChat = null;
                        return true;
                    }
                    ///////////


//                    WxUiViewConfig.printViewGroup((ViewGroup) v);
//                    View searchResult = WxUiViewConfig.getViewByIdAndContent((ViewGroup) v, WxUiViewConfig.ID_SEARCH_NICK_NAME_RESULT_CONTENT, searchName.toString());
//                    LogManager.getInstance().logInfo("查找聊天昵称的View = " + searchResult);
//                    if (null != searchResult) {
//                        ViewOperation.clickView(searchResult);
//                    } else {
////                        sendBackEvent(v.getContext());
//                        LogManager.getInstance().logError("没有搜索到消息");
//
//                        Bundle bundle = new Bundle();
//                        bundle.putString(TaskLogicService.KEY_ERROR_MESSAGE, "没有搜索到好友 type " + mNewChat.getType() + " content = " + mNewChat.getContent());
//                        Intent errorIntent = new Intent(TaskLogicService.ACTION_REPORT_SYSTEM_ERROR);
//                        errorIntent.putExtras(bundle);
//                        v.getContext().sendBroadcast(errorIntent);
//
//                        if (null != mNewChat) {
//                            boolean deleteMessage = ChatMessageBean.deleteChatMessage(v.getContext(), mNewChat.getId());
//                            LogManager.getInstance().logInfo("删除消息 " + deleteMessage + " id = " + mNewChat.getId());
//                            sendBackEvent(v.getContext());
//                            mNewChat = null;
//                        }
//                        return true;
//                    }
                } else {
                    ViewOperation.setText(editText, mNewChat.getNickName());
                }
            }
        } else if (WxUiViewConfig.CHAT_UI.equals(contextName)) {
//            WxUiViewConfig.printViewGroup((ViewGroup) v);
            if (null == mNewChat) {
//                sendBackEvent(v.getContext());
                View backButton = v.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
                if (null != backButton) {
                    ViewOperation.clickView(backButton);
                }
                return true;
            } else {
                sendChatViewProcess((ViewGroup) v);
            }
        } else if (WxUiViewConfig.VIEW_SUBSCRIBE_LIST.equals(contextName)) {
            View backButton = v.findViewById(WxUiViewConfig.ID_SUBSCRIBE_LIST_BACK);
            if (null != backButton) {
                ViewOperation.clickView(backButton);
            }
        } else if (WxUiViewConfig.DIALOG_CLASS.equals(contextName)) {
            View info = v.findViewById(WxUiViewConfig.DIALOG_INFO_TEXT);
            if (null != info) {
                TextView tv = (TextView) info;
                String promptMessage = tv.getText().toString();
                if ("用户不存在".equals(promptMessage)) {
                    LogManager.getInstance().logError("搜索的用户不存在");
                    if (null != mNewChat) {
                        boolean deleteMessage = ChatMessageBean.deleteChatMessage(v.getContext(), mNewChat.getId());
                        LogManager.getInstance().logInfo("删除消息 " + deleteMessage);
                        sendBackEvent(v.getContext());
                        mNewChat = null;
                    }
                    sendBackEvent(v.getContext());
                    return true;
                }
            }
        } else if (WxUiViewConfig.VIEW_TENCENT_NEWS.equals(contextName)) { //腾讯新闻
            TaskLogicService.sendKeyEvent(v.getContext(), TaskLogicService.INPUT_TYPE_BACK);
            return true;
        } else if (WxUiViewConfig.VIEW_ALBUM_PREVIEW.equals(contextName)) {
//            WxUiViewConfig.printViewGroup((ViewGroup) v);
            View gridView = v.findViewById(WxUiViewConfig.GRID_VIEW);
            if (null != gridView && gridView instanceof GridView) {
                ViewGroup gridGroup = (ViewGroup) gridView;
                if (gridGroup.getChildCount() > 1) {
                    View secondView = gridGroup.getChildAt(1);
                    if (null != secondView) {
                        ViewOperation.clickView(secondView);
                    }
                }
            }

        } else if (WxUiViewConfig.VIEW_SELECT_PIC.equals(contextName)) {
            View send = v.findViewById(2131624139);
            if (null != send) {
                LogManager.getInstance().logError("click send view");
                ViewOperation.clickView(send);
//                Context context = send.getContext();
//                LogManager.getInstance().logError("VIEW_SELECT_PIC context = " + context + " " + (context instanceof Activity));
//
//                if (context instanceof  Activity) {
//                    final Activity activity = (Activity) context;
//                    send.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            activity.finish();
//                        }
//                    },1000);
//
//                }
//                Class cls = context.getClass();
//                while (null != cls) {
//                    LogManager.getInstance().logInfo("cls = " + cls);
//                    cls = cls.getSuperclass();
//                }
            }
        } else if (WxUiViewConfig.VIEW_CONTACT_INFO_UI.equals(contextName)) {
            File imageFile = new File(ReportIcon.iconPath + "/" + needReportIconUserName + ".jpg");
            String savedIconPath = "";
            if (imageFile.exists()) {
                LogManager.getInstance().logError("文件已经存在 " + imageFile.getName());
//                ChatFriendBean.updateIconPath(v.getContext(), needReportIconUserName);
                savedIconPath = imageFile.getAbsolutePath();
            } else {
                final View image = v.findViewById(2131624265);
                if (null != image) {
                    image.buildDrawingCache();
                    image.setDrawingCacheEnabled(true);
                    Bitmap bitmap = Bitmap.createBitmap(image.getDrawingCache());  //获取到Bitmap的图片
                    image.setDrawingCacheEnabled(false);
                    if (null != bitmap) {
                        boolean savePic = ReportIcon.saveFriendIcon(bitmap, needReportIconUserName);
                        if (savePic) {
//                            ChatFriendBean.updateIconPath(image.getContext(), currentWxId);
                            savedIconPath = imageFile.getAbsolutePath();
                        }
                    }
                }
            }

            View sexView = v.findViewById(2131625130);
            String sex = ReportMessage.SEX_TYPE_NONE;
            if (null != sexView) {
                CharSequence desCharSequence = sexView.getContentDescription();
                if (null != desCharSequence) {
                    sex = desCharSequence.toString();
                }
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put("coverPath", savedIconPath);
            contentValues.put("isMale", sex);
            int updateId = v.getContext().getContentResolver().update(friendsUri, contentValues, "username=?", new String[]{needReportIconUserName});
            LogManager.getInstance().logInfo("update friend coverPath = " + savedIconPath + " 性别 = " + sex + " updateId = " + updateId);
            sendBackEvent(v.getContext());
            //-------------------------------------------------------------------------------------------------------------------------------------

          /*  final View image = v.findViewById(2131624265);
//            WxUiViewConfig.printViewGroup((ViewGroup) v);
            if (null != image) {
                image.buildDrawingCache();

                image.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(image.getDrawingCache());  //获取到Bitmap的图片
                image.setDrawingCacheEnabled(false);

                if (null != bitmap) {
                    boolean savePic = ReportIcon.saveFriendIcon(bitmap, currentWxId);
                    if (savePic) {
                        ChatFriendBean.updateIconPath(image.getContext(), currentWxId);
                    }
                }
                View sexView = v.findViewById(2131625130);
                LogManager.getInstance().logInfo("sexView = " + sexView);
                String sex = ReportMessage.SEX_TYPE_NONE;
                if (null != sexView) {
                    CharSequence desCharSequence = sexView.getContentDescription();
                    LogManager.getInstance().logInfo("desCharSequence = " + desCharSequence);
                    if (null != desCharSequence) {
                        sex = desCharSequence.toString();
//                        String sexTag = desCharSequence.toString();
//                        LogManager.getInstance().logInfo("sexTag = " + sexTag);
//                        if (!TextUtils.isEmpty(sexTag)) {
//                            if ("女".equals(sexTag)) {
//                                sex = ReportMessage.SEX_TYPE_FE_MALE;
//                            } else if ("男".equals(sexTag)) {
//                                sex = ReportMessage.SEX_TYPE_MALE;
//                            }
//                        }
                    }
                }

                Intent intent = new Intent(TaskLogicService.ACTION_KEY_REPORT_FRIEND_SEX);
                Bundle bundle = new Bundle();
                bundle.putString(TaskLogicService.KEY_SEX_TALKER, needReportIconUserName);
                bundle.putString(TaskLogicService.KEY_SEX_SEX, sex);
                intent.putExtras(bundle);
                v.getContext().sendBroadcast(intent);
                sendBackEvent(image.getContext());
            }*/
        } else if (WxUiViewConfig.VIEW_LUCKY_MONEY_RECEIVE.equals(contextName)) {
            View receive = v.findViewById(WxUiViewConfig.RECEIVE_MONEY);
            if (null != receive) {
                ViewOperation.clickView(receive);
            }
        } else if (WxUiViewConfig.VIEW_LUCKY_MONEY_DETAIL.equals(contextName)) {
//            WxUiViewConfig.printViewGroup((ViewGroup) v);
            View moneyNumber = v.findViewById(WxUiViewConfig.RECEIVE_MONEY_NUM);
            if (moneyNumber != null && moneyNumber instanceof TextView) {
                TextView moneyText = (TextView) moneyNumber;
                String number = moneyText.getText().toString();
                LogManager.getInstance().logInfo("收到多少钱 " + number);
                float getMoney = 0;
                try {
                    getMoney = Float.parseFloat(number);
                } catch (NumberFormatException e) {
                    LogManager.getInstance().logError("解析红包出错 " + e);
                    sendBackEvent(v.getContext());
                }
                if (getMoney > 0) {
                    receiveMoney = getMoney;
                    processReceiveHongBao(v, clickHongbaoOrZhuanZhangItem, getMoney);
                    waitOneStemp = true;
                    sendBackEvent(v.getContext());
                    return true;
                }
            }
        } else if (WxUiViewConfig.VIEW_RECEIVE_MONEY.equals(contextName)) {

            View receive = v.findViewById(WxUiViewConfig.SURE_RECEIVE_MONEY);
            if (null != receive && receive.getVisibility() == View.VISIBLE) {
                ViewOperation.clickView(receive);
            } else {
                View numView = v.findViewById(2131627297);
                if (numView != null && numView instanceof TextView) {
                    TextView moneyText = (TextView) numView;
                    String number = moneyText.getText().toString();
                    number = number.replace("￥", "");
                    LogManager.getInstance().logInfo("收到多少钱 " + number);
                    float getMoney = 0;
                    try {
                        getMoney = Float.parseFloat(number);
                    } catch (NumberFormatException e) {
                        LogManager.getInstance().logError("解析转账出错 " + e);
                    }
                    if (getMoney > 0) {
                        receiveMoney = getMoney;
//                        sendChat(v.getContext(), lastReceiveMoneyName, lastReceiveMoneyItem);
                        lastReceiveMoneyName = "";
                        lastReceiveMoneyItem = null;

                        processReceiveHongBao(v, clickHongbaoOrZhuanZhangItem, getMoney);
                        waitOneStemp = true;
                        sendBackEvent(v.getContext());
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private HashSet<Integer> hasSendPicId = new HashSet<>();
    private float receiveMoney = 0; //// TODO: 2017/3/22 查找消息处理完毕，删掉这类代码

    /**
     * 有新消息，发送消息
     *
     * @param chatViewGroup
     * @return
     */
    @SuppressWarnings("ResourceType")
    private boolean sendChatViewProcess(ViewGroup chatViewGroup) {
        HideKeyboard(chatViewGroup);
        /**
         * START 此处添加一个处理，在微商版本中，可能需要聊的人不同，做一个判断，是否是当前聊的人
         */
//        View title = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_NICK_NAME_TITLE);
//        if (null != title && title instanceof TextView) {
//            TextView titleView = (TextView) title;
//            String nickName = titleView.getText().toString();
//            Object searchName = mNewChat.getNickName();
//            if (null != searchName) {
//                if (searchName.toString().equals(nickName)) {
//                    LogManager.getInstance().logInfo("聊天的人是同一个");
//                } else {
//                    LogManager.getInstance().logInfo("聊天不是同一个人");
//                    View backButton = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
//                    if (null != backButton) {
//                        ViewOperation.clickView(backButton);
//                    }
//                    return false;
//                }
//            } else {
//                LogManager.getInstance().logInfo("聊天人的昵称是" + searchName);
//            }
//        } else {
//            LogManager.getInstance().logInfo("没有找到标题");
//        }

        View listView = chatViewGroup.findViewById(2131624768);
        LogManager.getInstance().logInfo("listView = " + listView);
        if (null == listView) {
            LogManager.getInstance().logError("reportNewMessage null == listView");
            return false;
        }

        ListView lv = (ListView) listView;
        Adapter adapter = lv.getAdapter();

        String field_talker = getCurrentChatWxId(lv);
        if (TextUtils.isEmpty(mNewChat.getTalker())) {
            boolean deleteMessage = ChatMessageBean.deleteChatMessage(chatViewGroup.getContext(), mNewChat.getId());
            LogManager.getInstance().logInfo("删除消息 " + deleteMessage + " id = " + mNewChat.getId());
            mNewChat = null;
            return false;
        }

        if (!mNewChat.getTalker().equals(field_talker)) {
            LogManager.getInstance().logError("聊天的不是同一个人  mNewChat.getTalker() = " + mNewChat.getTalker() + " current talker = " + field_talker);
            View backButton = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
            if (null != backButton) {
                ViewOperation.clickView(backButton);
            }
            return true;
        }


        /**
         * END 此处添加一个处理，在微商版本中，可能需要聊的人不同，做一个判断，是否是当前聊的人
         */
        if (mNewChat.getType() == ReportMessage.MESSAGE_TYPE_VOICE) {
            Intent intent = new Intent(WxTaskManger.ACTION_ADD_EXTRA_VOICE_PATH);
            Bundle bundle = new Bundle();
            bundle.putString(HookAudioRecord.KEY_AUDIO_PATH, mNewChat.getFilePath());
            intent.putExtras(bundle);
            chatViewGroup.getContext().sendBroadcast(intent);
            LogManager.getInstance().logInfo("发送录音路径 " + mNewChat.getFilePath());
//            WxUiViewConfig.printViewGroup( );

            View pressTalk = chatViewGroup.findViewById(2131624796);//按住说话
            if (null != pressTalk && pressTalk.getVisibility() == View.VISIBLE) {
                LogManager.getInstance().logInfo("开始按住说话");
                ViewOperation.PressDownView(pressTalk);
                boolean deleteMessage = ChatMessageBean.deleteChatMessage(chatViewGroup.getContext(), mNewChat.getId());
                LogManager.getInstance().logInfo("删除消息 " + deleteMessage);
                mNewChat = null;
            } else {//按住可以说话
                View switch2Talk = chatViewGroup.findViewById(2131624792);
                if (null != switch2Talk && switch2Talk.getVisibility() == View.VISIBLE) {
                    ViewOperation.clickView(switch2Talk);
                }
            }

        } else if (mNewChat.getType() == ReportMessage.MESSAGE_TYPE_PICTURE) {
            Intent intent = new Intent(WxTaskManger.ACTION_ADD_EXTRA_ICON);
            Bundle bundle = new Bundle();
            bundle.putString(WxUiViewConfig.KEY_SEND_PIC_MESSAGE, mNewChat.getFilePath());
            intent.putExtras(bundle);
            chatViewGroup.getContext().sendBroadcast(intent);
            LogManager.getInstance().logInfo("发送图片 " + mNewChat.getFilePath());


            View sendPic = chatViewGroup.findViewById(WxUiViewConfig.SEND_PIC);
            if (null != sendPic && sendPic.getVisibility() == View.VISIBLE) {
                ViewOperation.clickView(sendPic);
                LogManager.getInstance().logError("发送图片消息成功 ,因为不在 主线程 所以会没有" + " mNewChat id = " + mNewChat.getId() + " process name = " + MockServices.getProcessName());
                if (null != mNewChat) {
                    try {
                        boolean deleteMessage = ChatMessageBean.deleteChatMessage(chatViewGroup.getContext(), mNewChat.getId());
                        LogManager.getInstance().logInfo("删除消息 " + deleteMessage);
                        mNewChat = null;
                    } catch (Exception e) {
                        LogManager.getInstance().logError(e.toString());
                    }
                } else {
                    LogManager.getInstance().logError("发送图片消息成功 null == mNewChat process = " + MockServices.getProcessName());
                }
            } else {
                View more = chatViewGroup.findViewById(WxUiViewConfig.MORE_FUNCTION);
                if (null != more) {
                    ViewOperation.clickView(more);
                }
            }

        } else {
            View inputView = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_EDIT_TEXT);
            if (null != inputView && inputView instanceof EditText) {
                EditText editText = (EditText) inputView;
                String currentInputContent = editText.getText().toString();
                if (TextUtils.isEmpty(currentInputContent)) {
                    ViewOperation.setText(inputView, mNewChat.getContent());
                } else {
                    View sendButton = chatViewGroup.findViewById(WxUiViewConfig.CHAT_VIEW_SEND_BUTTON);
                    if (null != sendButton) {
                        ViewOperation.clickView(sendButton);
                        boolean deleteMessage = ChatMessageBean.deleteChatMessage(chatViewGroup.getContext(), mNewChat.getId());
                        LogManager.getInstance().logInfo("删除消息 " + deleteMessage);
                        mNewChat = null;
                        if (null == mNewChat) {
                            mNewChat = ChatMessageBean.getNewChat(chatViewGroup.getContext());
                        }
                        if (null == mNewChat) {
                            sendBackEvent(chatViewGroup.getContext());
                        }
                    }
                }
            }
        }
        return false;
    }

    //隐藏虚拟键盘
    public static void HideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    private String lastReceiveMoneyName = "";
    private Object lastReceiveMoneyItem = null;

    private String getCurrentChatWxId(ListView listView) {
        if (null == listView) {
            return "";
        }
        Adapter adapter = listView.getAdapter();

        for (int i = adapter.getCount() - 1; i > 0; i--) {
            Object item = adapter.getItem(i);
//            LogManager.getInstance().logInfo("item = " + item);
            Object talkerObj = getObjField(item, "field_talker");
            if (null != talkerObj) {
                return talkerObj.toString();
            }
        }
        return "";
    }

    private boolean hasScrollNext = false;

    /**
     * 最后一行消息单独处理，避免是红包等需要操作的任务的时候，显示一小部分，导致点击失败，
     *
     * @param item
     * @return
     */
    private boolean needScrollNext(Object item) {
        Object typeObj = getObjField(item, "field_type");
        if (null != typeObj && typeObj instanceof Integer) {
            int type = (int) typeObj;
            if (ReportMessage.MESSAGE_TYPE_HONG_BAO == type || ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG == type) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings("ResourceType")
    private boolean processReceiveHongBao(View v, Object item, float receiverMoney) {

        String talker = (String) getObjField(item, "field_talker");
        long createTime = (long) getObjField(item, "field_createTime");
        String imgPath = (String) getObjField(item, "field_imgPath");
        String content = (String) getObjField(item, "field_content");
        int type = (int) getObjField(item, "field_type");

        if (type == ReportMessage.MESSAGE_TYPE_HONG_BAO) {
            content = "收到红包[{[{" + receiverMoney + "}]}]";
        } else if (type == ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG) {
            content = "收到转账[{[{" + receiverMoney + "}]}]";
        } else {
            LogManager.getInstance().logError("点击了不是红包的消息  红包呢  红包呢  红包呢  红包呢  红包呢  ，转账呢 转账呢 转账呢 转账呢");
            return false;
        }

        boolean reportNow = true; //标志是否立马上报

        Cursor cursor = v.getContext().getContentResolver().query(friendsUri, null, "username=? and updated=1", new String[]{talker}, null);
        if (null != cursor && cursor.getCount() <= 0) {
            LogManager.getInstance().logInfo("发送消息 好友未上报");
            needSyncBaseFriend = true;
            needSyncFriend = true;
            reportNow = false;
            cursor.close();
        }

        Intent i = new Intent(TaskLogicService.ACTION_KEY_REPORT_CHAT);
        Bundle bundle = new Bundle();
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_TALKER, talker);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_NIKE_NAME, clickHongbaoNike);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_IMG_PATH, imgPath);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_CONTENT, content);
        bundle.putLong(TaskLogicService.KEY_REPORT_CHAT_CREATE_TIME, createTime);
        bundle.putInt(TaskLogicService.KEY_REPORT_CHAT_TYPE, type);
        bundle.putBoolean(TaskLogicService.KEY_REPORT_NOW, reportNow);
        i.putExtras(bundle);
        v.getContext().sendBroadcast(i);

        return false;
    }

    /**
     * 处理消息手机接收到的消息。
     *
     * @param v
     * @param item
     * @return 是否需要继续执行，  当点击红包的时候，例如就不需要继续执行了
     */
    @SuppressWarnings("ResourceType")
    private boolean processReceivedMessage(View v, Object item) {
        View nikeView = v.findViewById(2131624143);
        String nike = "";
        if (null != nikeView && nikeView instanceof TextView) {
            nike = ((TextView) nikeView).getText().toString();
        }

        String talker = (String) getObjField(item, "field_talker");
        long createTime = (long) getObjField(item, "field_createTime");
        String imgPath = (String) getObjField(item, "field_imgPath");
        String content = (String) getObjField(item, "field_content");
        int type = (int) getObjField(item, "field_type");

        LogManager.getInstance().logError("processReceivedMessage type = " + type + " createTime = " + createTime + " imgPath = " + imgPath + " content = " + content);
        if (null != content && type == ReportMessage.MESSAGE_TYPE_WARING && content.contains("你领取了") && content.contains("红包")) {
            //领取了红包
            content = "红包确认消息";
            receiveMoney = 0;
        } /*else if (null != content && type == ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG) {
            //领取了红包
            content = "收到转账{" + receiveMoney + "}";
            receiveMoney = 0;
        }*/
        if (type == ReportMessage.MESSAGE_TYPE_HONG_BAO) {
            content = "收到红包消息";
            clickHongbaoNike = nike;
        } else if (type == ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG) {
            content = "收到转账";
            clickHongbaoNike = nike;
        }


        boolean reportNow = true; //标志是否立马上报

        Cursor cursor = v.getContext().getContentResolver().query(friendsUri, null, "username=? and updated=1", new String[]{talker}, null);
        if (null != cursor && cursor.getCount() <= 0) {
            LogManager.getInstance().logInfo("发送消息 好友未上报");
            needSyncBaseFriend = true;
            needSyncFriend = true;
            reportNow = false;
            cursor.close();
        } else {
//            LogManager.getInstance().logInfo("发送消息 好友 已经上报");
        }

        Intent i = new Intent(TaskLogicService.ACTION_KEY_REPORT_CHAT);
        Bundle bundle = new Bundle();
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_TALKER, talker);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_NIKE_NAME, nike);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_IMG_PATH, imgPath);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_CONTENT, content);
        bundle.putLong(TaskLogicService.KEY_REPORT_CHAT_CREATE_TIME, createTime);
        bundle.putInt(TaskLogicService.KEY_REPORT_CHAT_TYPE, type);
        bundle.putBoolean(TaskLogicService.KEY_REPORT_NOW, reportNow);
//        LogManager.getInstance().logInfo("KEY_REPORT_NOW = " + reportNow);
        i.putExtras(bundle);
        v.getContext().sendBroadcast(i);
        if (type == ReportMessage.MESSAGE_TYPE_HONG_BAO || type == ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isReceivedMessage(Object item) {
        Object field_isSend_Obj = getObjField(item, "field_isSend");
        if (null != field_isSend_Obj && field_isSend_Obj instanceof Integer && (int) field_isSend_Obj == 0) {
            return true;
        }
        return false;
    }

    private long getItemTime(Object item) {
        Object field_createTime_Obj = getObjField(item, "field_createTime");
        if (null != field_createTime_Obj && field_createTime_Obj instanceof Long)
            return (long) field_createTime_Obj;
        return -1;
    }

    private void scrollUp(ListView listView) {
//        ViewOperation.moveHalfScreenUp(listView);
        int firstPosition = listView.getFirstVisiblePosition();
        int lastPosition = listView.getLastVisiblePosition();

        int halfScreenNum = (lastPosition - firstPosition) / 2;

        if (halfScreenNum <= 1) {
            halfScreenNum = 1;
        }

        int scrollEnd = firstPosition - halfScreenNum;
        if (scrollEnd <= 0) {
            scrollEnd = 0;
        }
        LogManager.getInstance().logError("scrollUp scrollEnd = " + scrollEnd);
        ViewOperation.moveListPosition(listView, scrollEnd);
    }

    private void scrollNext(ListView listView) {
//        ViewOperation.moveHalfScreenNext(listView);
        int firstPosition = listView.getFirstVisiblePosition();
        int lastPosition = listView.getLastVisiblePosition();

        int halfScreenNum = (lastPosition - firstPosition) / 2;

        if (halfScreenNum <= 1) {
            halfScreenNum = 1;
        }

        int scrollEnd = firstPosition + halfScreenNum;
        if (scrollEnd > lastPosition) {
            scrollEnd = lastPosition;
        }
        LogManager.getInstance().logError("scrollNext scrollEnd = " + scrollEnd);
        ViewOperation.moveListPosition(listView, scrollEnd);
    }

    /**
     * 聊天界面打开了，上报新消息
     * 主要考虑是否在检查新消息的时候，来的新的消息。
     *
     * @param v
     * @return
     */
    @SuppressWarnings("ResourceType")
    private boolean reportNewMessage(ViewGroup v) {
//        WxUiViewConfig.printViewGroup(v);
        HideKeyboard(v);

        View listView = v.findViewById(2131624768);
        LogManager.getInstance().logInfo("listView = " + listView);
        if (null == listView) {
            LogManager.getInstance().logError("reportNewMessage null == listView");
            return false;
        }

        ListView lv = (ListView) listView;
        Adapter adapter = lv.getAdapter();

//            LogManager.getInstance().logInfo("adapter = " + adapter);
//            LogManager.getInstance()fdffdfdsf("adapter.getCount() = " + adapter.getCount());

        String field_talker = getCurrentChatWxId(lv);
        //先拿到微信id
        LogManager.getInstance().logInfo("微信ID = " + field_talker);
        if (TextUtils.isEmpty(field_talker)) {
            LogManager.getInstance().logError("获取field_talker 失败");
            return false;
        }

        long lastSendTime = LastUpdateDB.getChatLastTime(v.getContext(), field_talker);
        if (lastSendTime <= 0) {
            LogManager.getInstance().logError("这个好友 之前不存在的消息");
        }

        LogManager.getInstance().logInfo("最后说话时间 =  " + lastSendTime);
        int lastMessagePosition = adapter.getCount();
        /**
         * 拿到最后消息的地方 start
         */
        if (LastUpdateDB.GET_LAST_TIME_FAIL == lastSendTime) {
            //// 2016/12/18 第一次数据库有记录的谈话 ,使用最后一次发送的消息
            for (int i = adapter.getCount() - 1; i > 0; i--) {
                Object item = adapter.getItem(i);
                Object field_isSend_Obj = getObjField(item, "field_isSend");
                if (null == field_isSend_Obj) {
                    continue;
                }
                if (field_isSend_Obj instanceof Integer) {
                    int isSend = (int) field_isSend_Obj;
                    if (isSend == 0) { //自己的消息
                        lastMessagePosition = i;
                        break;
                    }
                } else {
                    LogManager.getInstance().logError("null != field_isSend_Obj && field_isSend_Obj instanceof Integer   field_isSend_Obj =  " + field_isSend_Obj + "   field_isSend_Obj  class = " + (field_isSend_Obj != null ? field_isSend_Obj.getClass() : null));
                }
            }
        } else {
            for (int i = adapter.getCount() - 1; i > 0; i--) {
                Object item = adapter.getItem(i);
                Object field_isSend_Obj = getObjField(item, "field_isSend");
                if (null == field_isSend_Obj) {
                    continue;
                }
                if (field_isSend_Obj instanceof Integer) {
                    int isSend = (int) field_isSend_Obj;
                    if (isSend == 0) { //对方发送的消息
                        Object field_createTime_Obj = getObjField(item, "field_createTime");
                        if (null != field_createTime_Obj && field_createTime_Obj instanceof Long) {
                            long messageCreateTime = (long) field_createTime_Obj;
                            if (messageCreateTime > lastSendTime) {
                                LogManager.getInstance().logInfo("需要上报的时间 = " + messageCreateTime);
                                lastMessagePosition = i;
                            } else {
                                break;
                            }
                        } else {
                            LogManager.getInstance().logError("null != field_createTime_Obj && field_createTime_Obj instanceof Long   field_createTime_Obj =  " + field_createTime_Obj + "   field_createTime_Obj  class = " + (field_createTime_Obj != null ? field_createTime_Obj.getClass() : null));
                        }
                    }
                } else {
                    LogManager.getInstance().logError("null != field_isSend_Obj && field_isSend_Obj instanceof Integer   field_isSend_Obj =  " + field_isSend_Obj + "   field_isSend_Obj  class = " + (field_isSend_Obj != null ? field_isSend_Obj.getClass() : null));
                }
            }
        }
        /**
         * 拿到最后消息的地方 end
         */
        int lastReportItem = 0;
        for (int i = lastMessagePosition, len = adapter.getCount(); i < len; i++) {
            Object item = adapter.getItem(i);
            Object field_isSend_Obj = getObjField(item, "field_isSend");
            if (null == field_isSend_Obj) {
                continue;
            }

            if (field_isSend_Obj instanceof Integer) {
                int isSend = (int) field_isSend_Obj;
                if (isSend == 0) { //对方发送的消息
                    long createTime = (long) getObjField(item, "field_createTime");
                    LastUpdateDB.updateChatLastTime(v.getContext(), field_talker, createTime);
                    lastReportItem = i;
                    View nikeName = v.findViewById(2131624143);
                    String nike = null;
                    if (null != nikeName && nikeName instanceof TextView) {
                        nike = ((TextView) nikeName).getText().toString();
                    }
                    if (!TextUtils.isEmpty(nike)) {
                        int type = (int) getObjField(item, "field_type");
                        if (type == ReportMessage.MESSAGE_TYPE_HONG_BAO) {
                            clickHongbao(lv, i);
                            return true;
                        } else if (type == ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG) {
                            clickHongbao(lv, i);
                            lastReceiveMoneyName = nike;
                            lastReceiveMoneyItem = item;
                            return true;
                        }
                        sendChat(v.getContext(), nike, item);
                    } else {
                        LogManager.getInstance().logError("获取昵称失败");
                    }
                }
            } else {
                LogManager.getInstance().logError("null != field_isSend_Obj && field_isSend_Obj instanceof Integer   field_isSend_Obj =  " + field_isSend_Obj + "   field_isSend_Obj  class = " + field_isSend_Obj.getClass());
            }
        }

        if (lastReportItem == adapter.getCount() - 1 || lastMessagePosition == adapter.getCount()) {
            LogManager.getInstance().logInfo("所有消息发送完毕 ");

            View backButton = v.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
            if (null != backButton) {
                ViewOperation.clickView(backButton);
            }
        }


        return false;
    }

    private void printMessage(Adapter adapter) {
        for (int i = adapter.getCount() - 1; i > 0; i--) {
            Object item = adapter.getItem(i);
            Object field_isSend_Obj = getObjField(item, "field_isSend");
            String talker = (String) getObjField(item, "field_talker");
            long createTime = (long) getObjField(item, "field_createTime");
            String imgPath = (String) getObjField(item, "field_imgPath");
            String content = (String) getObjField(item, "field_content");
            int type = (int) getObjField(item, "field_type");

            LogManager.getInstance().logInfo("field_isSend_Obj = " + field_isSend_Obj + " talker = " + talker + " type = " + type + " content = " + content + " imgPath = " + imgPath);
        }
    }

    private void clickHongbao2(ListView listView, int Position) {
        int first = listView.getFirstVisiblePosition();
        int last = listView.getLastVisiblePosition();
        LogManager.getInstance().logInfo("clickHongbao2  first = " + first + " last = " + last + " Position = " + Position);

        View clickView = listView.getChildAt(Position - first);
        LogManager.getInstance().logInfo("clickView " + clickView);
        ViewOperation.clickView(clickView);
//        for (int i = 0; i < listView.getChildCount(); i++) {
//            LogManager.getInstance().logInfo("--------------------------");
//            LogManager.getInstance().logInfo("listView.getChildAt(i)) position = " + i + "  view = " + listView.getChildAt(i));
//            ClassTool.justPrintAllField(listView.getChildAt(i));
//            LogManager.getInstance().logInfo("--------------------------");
//        }
    }

    private void clickHongbao(ListView listView, int Position) {
        int first = listView.getFirstVisiblePosition();
        int last = listView.getLastVisiblePosition();
        LogManager.getInstance().logInfo("first = " + first + " last = " + last + " Position = " + Position);

        for (int i = 0; i < listView.getChildCount(); i++) {
            LogManager.getInstance().logInfo("--------------------------");
            LogManager.getInstance().logInfo("listView.getChildAt(i)) = " + listView.getChildAt(i));

            LogManager.getInstance().logInfo("--------------------------");
        }
        View v = listView.getChildAt(listView.getChildCount() - (listView.getCount() - Position));
        LogManager.getInstance().logInfo("clickHongbao view = " + v);

        ViewOperation.clickView(v);
    }

    public void sendChat(Context context, String nikeName, Object item) {
        String talker = (String) getObjField(item, "field_talker");
        long createTime = (long) getObjField(item, "field_createTime");
        String imgPath = (String) getObjField(item, "field_imgPath");
        String content = (String) getObjField(item, "field_content");
        int type = (int) getObjField(item, "field_type");

        if (null != content && type == ReportMessage.MESSAGE_TYPE_WARING && content.contains("你领取了") && content.contains("红包")) {
            //领取了红包
            content = "已领取红包{" + receiveMoney + "}";
            type = ReportMessage.MESSAGE_TYPE_HONG_BAO;
            receiveMoney = 0;
        } else if (null != content && type == ReportMessage.MESSAGE_TYPE_ZHUAN_ZHANG) {
            //领取了红包
            content = "收到转账{" + receiveMoney + "}";
            receiveMoney = 0;
        }
        boolean reportNow = true; //标志是否立马上报

        Cursor cursor = context.getContentResolver().query(friendsUri, null, "username=? and updated=1", new String[]{talker}, null);
        if (null != cursor && cursor.getCount() <= 0) {
            LogManager.getInstance().logInfo("发送消息 好友未上报");
            needSyncBaseFriend = true;
            needSyncFriend = true;
            reportNow = false;
            cursor.close();
        } else {
            LogManager.getInstance().logInfo("发送消息 好友 已经上报");
        }

        Intent i = new Intent(TaskLogicService.ACTION_KEY_REPORT_CHAT);
        Bundle bundle = new Bundle();
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_TALKER, talker);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_NIKE_NAME, nikeName);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_IMG_PATH, imgPath);
        bundle.putString(TaskLogicService.KEY_REPORT_CHAT_CONTENT, content);
        bundle.putLong(TaskLogicService.KEY_REPORT_CHAT_CREATE_TIME, createTime);
        bundle.putInt(TaskLogicService.KEY_REPORT_CHAT_TYPE, type);
        bundle.putBoolean(TaskLogicService.KEY_REPORT_NOW, reportNow);
        LogManager.getInstance().logInfo("KEY_REPORT_NOW = " + reportNow);
        i.putExtras(bundle);
        context.sendBroadcast(i);
    }

    public static Object getObjField(Object object, String name) {
        if (null == object) {
            return null;
        }
        try {
            Field field = object.getClass().getField(name);
            field.setAccessible(true);
            return field.get(object);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void sendBackEvent(Context context) {
        Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
        Bundle bundle = new Bundle();
        bundle.putInt(TaskLogicService.KEY_INPUT_KEY, TaskLogicService.INPUT_TYPE_BACK);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }


    private String needReportIconUserName = null;


    @SuppressWarnings("ResourceType")
    private boolean syncFriend(View v) {

        View chatViewGroupView = v.findViewById(WxUiViewConfig.CHAT_VIEW_GROUP_VIEW);
//            LogManager.getInstance().logInfo("chatViewGroupView " + chatViewGroupView + (null == chatViewGroupView ? "null == chatViewGroupView  " : " null == chatViewGroupView visual " + chatViewGroupView.getVisibility()));
        if (null != chatViewGroupView && chatViewGroupView.getVisibility() == View.VISIBLE) {
            //聊天界面已经打开
            LogManager.getInstance().logInfo("聊天界面已经打开");
            View backButton = v.findViewById(WxUiViewConfig.CHAT_VIEW_BACK_BUTTON);
            if (null != backButton) {
                ViewOperation.clickView(backButton);
            }
            return true;
        }
        if (WxUiViewConfig.inTab(v, WxUiViewConfig.TAB_CONTACTS)) {
            View listView = v.findViewById(2131624187);

            if (null != listView && listView instanceof ListView) {
                ListView lv = (ListView) listView;
                Adapter adapter = lv.getAdapter();
                if (needSyncBaseFriend) {
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0, len = adapter.getCount(); i < len; i++) {
                        Object o = adapter.getItem(i);
                        if (null != o) {
                            LogManager.getInstance().logInfo(adapter.getItem(i).toString());
                            ClassTool.printAllField(o);

                            JSONObject jo = new JSONObject();

                            Object remark = getObjField(o, "field_conRemark");
                            Object username = getObjField(o, "field_username");

                            Object nickname = getObjField(o, "field_nickname");
                            String remarkStr = (remark == null ? null : remark.toString());
                            LogManager.getInstance().logInfo("remarkStr = " + remarkStr);

                            if (!TextUtils.isEmpty(username == null ? null : username.toString()) && !TextUtils.isEmpty(nickname == null ? null : nickname.toString())) {
                                try {
                                    jo.put(ChatNewChatDB.KEY_FRIEND_USER_NAME, username.toString());
                                    if (TextUtils.isEmpty(remarkStr)) {
                                        jo.put(ChatNewChatDB.KEY_FRIEND_NIKE_NAME, nickname.toString());
                                    } else {
                                        jo.put(ChatNewChatDB.KEY_FRIEND_NIKE_NAME, remarkStr);
                                    }
                                    jsonArray.put(jo);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
//                    LogManager.getInstance().logInfo(jsonArray.toString());
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ChatNewMessageProvider.KEY_GET_INSERT_JSON, jsonArray.toString());
                    v.getContext().getContentResolver().insert(friendsUri, contentValues);
                    needSyncBaseFriend = false;
                    return true;
                }
                //基本信息插入完毕，在检查是否需要上传性别和图像

                Cursor cursor = v.getContext().getContentResolver().query(friendsUri, null, "coverPath='' or isMale='' ", new String[]{}, null);

                //找到需要上报的好友
                String needReportUser = "";
                if (null != cursor && cursor.getCount() > 0 && cursor.moveToNext()) {
                    needReportUser = cursor.getString(cursor.getColumnIndex("username"));
                    cursor.close();
                }

                if (!TextUtils.isEmpty(needReportUser)) { //有未上报的图像或者性别
                    for (int i = 0, len = adapter.getCount(); i < len; i++) {
                        Object o = adapter.getItem(i);
                        if (null != o) {
                            Object username = getObjField(o, "field_username");
                            if (null != username && !TextUtils.isEmpty(username.toString()) && username.equals(needReportUser)) {
                                LogManager.getInstance().logInfo("保存好友图片 getNickname = " + needReportUser + " getUsername = " + needReportUser + " position = " + i);
                                lv.getOnItemClickListener().onItemClick(lv, null, i, -1);
                                Object talkerObj = getObjField(o, "field_username");
                                if (null != talkerObj) {
                                    needReportIconUserName = username.toString();
                                }
                                return true;
                            }
                        }
                    }
                } else {
                    needSyncFriend = false;
                    //所有好友全部上报完毕，通知 上报好友
                    v.getContext().sendBroadcast(new Intent(FriendProvider.ACTION_REPORT_FRIENDS));
                }

                lastUpdate = System.currentTimeMillis();
            }
        } else {
            LogManager.getInstance().logInfo("需要同步好友但不再通讯录选项页面");
            return false;
        }
        return false;
    }


    private boolean needScrollNewMessageUpPosition = true;
    private boolean needClickSendMessageUpPosition = true;

    /**
     * 消息列表页面，检查是否有新消息 ,
     *
     * @param v
     * @return
     */
    @SuppressWarnings("ResourceType")
    private boolean checkNewMessage(View v) {
        View tagView = v.findViewWithTag(WxUiViewConfig.TAB_WEIXIN);
        if (null == tagView) {
            LogManager.getInstance().logError("checkNewMessage null == tagView  ");
            return false;
        }


        View weixinRedPositon = tagView.findViewById(WxUiViewConfig.TAB_ICO_NEW_MESSAGE_NUM);
        if (null != weixinRedPositon && weixinRedPositon.getVisibility() == View.VISIBLE) {
            //有红点新消息 在微信TAB页面

            View chatListView = v.findViewById(WxUiViewConfig.CHAT_LIST_VIEW);
            int newPosition = 0;
            View newMessageView = null;
            if (null != chatListView && chatListView instanceof ListView) {
                ListView chatLV = (ListView) chatListView;

                for (int i = 0, len = chatLV.getChildCount(); i < len; i++) {
                    View childView = chatLV.getChildAt(i);
//                    LogManager.getInstance().logInfo("||||||||||||||||||||||  position = " + i + "  getHeaderViewsCount = " + chatLV.getHeaderViewsCount());
//                    WxUiViewConfig.printViewGroup((ViewGroup) childView);
//                    LogManager.getInstance().logInfo("||||||||||||||||||||||  position = " + i + "  getHeaderViewsCount = " + chatLV.getHeaderViewsCount());
                    View chatNewNum = childView.findViewById(WxUiViewConfig.LIST_ITEM_NEW_MESSAGE_NUM);
                    if (null != chatNewNum && chatNewNum.getVisibility() == View.VISIBLE && chatNewNum instanceof TextView) {
                        TextView newTextNumView = (TextView) chatNewNum;
                        if (!TextUtils.isEmpty(newTextNumView.getText().toString())) {
                            if (i != 0 && i != chatLV.getChildCount() - 1) {
                                WxUiViewConfig.printViewGroup((ViewGroup) childView);
                                ViewOperation.clickView(childView); //找到item红点左边，就点击
                                needScrollNewMessageUpPosition = true;
                                LogManager.getInstance().logInfo("click postition = " + i + " count = " + chatLV.getChildCount());
                                return true;
                            } else {
                                newPosition = i;
                                newMessageView = childView;
                                break;
                            }
                        }
                    }
                }

                if (newPosition == 0) {
                    if (needScrollNewMessageUpPosition) {
                        LogManager.getInstance().logInfo("新消息 第一条  上滚 ");
                        scrollUp(chatLV);
                        needScrollNewMessageUpPosition = false;
                        return false;
                    } else {
                        LogManager.getInstance().logInfo("新消息 第一条   已经上滚动 ");
                        ViewOperation.clickView(newMessageView);
                        needScrollNewMessageUpPosition = true;
                        return true;
                    }
                }
            }


            if (null != weixinRedPositon && weixinRedPositon.getVisibility() == View.VISIBLE) {
                ViewOperation.doubleClickView(weixinRedPositon);
            }
        } else {
            //没有红点新消息，检查是否有发过来的消息
            if (null == mNewChat) {
                mNewChat = ChatMessageBean.getNewChat(v.getContext());
            }
            if (null == mNewChat) {
                LogManager.getInstance().logInfo("没有新消息需要发送");
                return false;
            }

            if (TextUtils.isEmpty(mNewChat.getTalker())) {
                boolean deleteMessage = ChatMessageBean.deleteChatMessage(v.getContext(), mNewChat.getId());
                LogManager.getInstance().logInfo("删除消息 " + deleteMessage + " id = " + mNewChat.getId());
                mNewChat = null;
                return false;
            }


            //从数据库中取出数据了
            View chatListView = v.findViewById(WxUiViewConfig.CHAT_LIST_VIEW);
            if (null != chatListView && chatListView instanceof ListView) {
                ListView chatLV = (ListView) chatListView;
                int first = chatLV.getFirstVisiblePosition();
                Adapter adapter = chatLV.getAdapter();
                View needChatView = null;

                int sendPosition = -1;
                for (int i = 0, len = chatLV.getChildCount() - 1; i < len; i++) {
//                    LogManager.getInstance().logInfo("---------------------------------------------------------------");
                    Object item = adapter.getItem(first + i);
                    Object username = getObjField(item, "field_username");

                    View childView = chatLV.getChildAt(i);
                    View chatItem = childView.findViewById(WxUiViewConfig.CHAT_LIST_ITEM);
                    if (mNewChat.getTalker() != null && mNewChat.getTalker().equals(username)) {
                        LogManager.getInstance().logInfo("找到发送好友位置    " + i + "mNewChat.getNickName() = " + mNewChat.getNickName() + " chatItem.getContentDescription() = " + chatItem.getContentDescription().toString() + " username = " + username + " mNewChat.getTalker()  = " + mNewChat.getTalker());
                        sendPosition = i;
                        if (sendPosition != 0) {
                            needClickSendMessageUpPosition = true;
//                            ViewOperation.clickView(childView);
//                            clickHongbao(chatLV,first + i);
                            chatLV.getOnItemClickListener().onItemClick(chatLV, null, first + i, first + i);
                            WxUiViewConfig.printViewGroup((ViewGroup) childView);
                            return true;
                        }
                        needChatView = childView;
                        break;
                    }
//                    LogManager.getInstance().logInfo("---------------------------------------------------------------");
                }

                if (sendPosition == 0) {
                    if (needClickSendMessageUpPosition) {
                        LogManager.getInstance().logInfo("新消息 第一条  上滚 ");
                        scrollUp(chatLV);
                        needClickSendMessageUpPosition = false;
                        return false;
                    } else {
                        LogManager.getInstance().logInfo("新消息 第一条   已经上滚动 ");
                        ViewOperation.clickView(needChatView);
                        needClickSendMessageUpPosition = true;
                        return true;
                    }
                }

                /**
                 * 没有找到要聊天的好友
                 */
                if (-1 == sendPosition) {
                    LogManager.getInstance().logError("没有找到好友， 点击搜索" + sendPosition + " getTalker =  " + mNewChat.getTalker() + "  getContent  = " + mNewChat.getContent());
                    WxUiViewConfig.clickSearchButton((ViewGroup) v);
                }


            }
        }
        return false;
    }


    private Object getSearUserName(Object item) {
        if (null == item) {
            LogManager.getInstance().logError("getSearUserName null == item");
            return null;
        }

        Class clazz = item.getClass();

        while (null != clazz) {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                try {
                    if ("username".equals(field.getName())) {
                        return field.get(item);
                    }
//                    LogManager.getInstance().logInfo("fieldName = " + field.getName() + " fieldObj = " + fieldObj + " class = " + (null == fieldObj ? " null " : fieldObj.getClass()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    LogManager.getInstance().logError("IllegalAccessException  fieldName = " + field.getName());
                }
            }
            clazz = clazz.getSuperclass();
        }
        return null;
    }

    private Object getSearchUserNamekOI(Object item) {
        if (null == item) {
            LogManager.getInstance().logError("getSearchUserNamekOI null == item");
            return null;
        }


        Object KOJ = ClassTool.getFiled(item, "kOI");
        if (null != KOJ) {
            LogManager.getInstance().logError("getSearchUserNamekOI null != kOI");
            Class cls = KOJ.getClass();
            while (null != cls) {
                LogManager.getInstance().logError("cls = " + cls);
                if ("com.tencent.mm.plugin.search.ui.a.b".equals(cls.getName())) {
                    LogManager.getInstance().logError("找到 com.tencent.mm.plugin.search.ui.a.b getSearchUserNamekOI");
                }
                cls = cls.getSuperclass();
            }
        }


        return null;
    }

    private Object getSearchUserNamekOJ(Object item) {
        if (null == item) {
            LogManager.getInstance().logError("getSearchUserNamekOI null == item");
            return null;
        }


        Object KOJ = ClassTool.getFiled(item, "kOJ");
        if (null != KOJ) {
            LogManager.getInstance().logError("getSearchUserNamekOI null != kOJ");
            Class cls = item.getClass();
            while (null != cls) {
                if ("com.tencent.mm.plugin.search.ui.a.b".equals(cls.getName())) {
                    LogManager.getInstance().logError("找到 com.tencent.mm.plugin.search.ui.a.b getSearchUserNamekOJ");
                }
            }
        }


        return null;
    }


}
